// const socketIO = require("socket.io");
const { Server } = require("socket.io");
const { handlerRTCFunction } = require("./handlerRTC");

const userlist = [];

const messageList = {};


// 追加用户列表
function addUserList(user) {
  const findindex = userlist.findIndex((item) => {
    return item.socketId == user.socketId;
  });
  if (findindex == -1) {
    userlist.push(user);
  }
}

// 获取用户列表 同时过滤自己的id
function getUserList(id) {
  const list = userlist;
  return list.filter((e) => e.socketId != id);
}

// 下线
function removeUserList(id) {
  const index = userlist.findIndex((item) => {
    return item.socketId == id;
  });
  if (index != -1) {
    userlist.splice(index, 1);
  }
}

function startSocketServer(httpServer) {
  const io = new Server(httpServer, {
    cors: {
      origin: "*",
      // origin: [
      //   "http://127.0.0.1:5173",
      //   "http://192.168.1.118:5173",
      //   "http://192.168.1.103:5173",
      //   "http://192.168.1.106:5173",
      //   "http://localhost:5173",
      // ],
    },
  });

  io.on("connection", (socket) => {
    console.log("有人上线了", socket.id);
    const userinfo = socket.handshake.query;

    const { username, now, avatar } = userinfo;
    const nowUserInfo = { username, socketId: socket.id, now, avatar };

    addUserList(nowUserInfo);

    !messageList[username] && (messageList[username] = []); //添加消息列表
    const nowMessageList = messageList[username];

    // 只在用户第一次上线时触发
    // 响应用户列表
    socket.emit("update-userlist", {
      userlist: getUserList(socket.id),
    });

    // 向所有人广播
    socket.broadcast.emit("update-userlist", { userlist: [nowUserInfo] });

    console.log("当前的用户列表>>>>", userlist);

    // 我要给别人发消息
    socket.on("user-say", (res) => {
      const { receiver, message } = res;
      // console.log(res)
      const messageObj = { receiver, message, sender: nowUserInfo };
      nowMessageList.push(messageObj);
      socket.to(receiver.socketId).emit("user-chat-private", messageObj);
      socket.emit("user-chat-private", messageObj);
    });
    socket.on("get-messagelist", (res, callback) => {
      const { id, loginValue } = res;
      callback(messageList[loginValue]);
    });

    socket.on("disconnect", () => {
      console.log("有人下线了", socket.id);
      removeUserList(socket.id);
      socket.broadcast.emit("user-logout", nowUserInfo);
    });

    handlerRTCFunction(socket);
  });
}

module.exports = {
  startSocketServer,
};
